package com.db.domain.bank;

import com.db.exceptions.NotEnoughFundsException;

public abstract class AbstractAccount implements Account {
    private static int accountCounter = 0;

    private int id;
    private double balance;

	public AbstractAccount(final double amount) {
		this.balance = amount;
        this.id = accountCounter++;
	}

    public void setBalance(double balance) {
        if(balance < 0) {
            throw new IllegalArgumentException("Negative initial balance");
        }
        this.balance = balance;
    }

    public double getBalance() {
        return balance;
    }

    @Override
    public void deposit(double amount) {
        balance += amount;
    }

    @Override
    public void withdraw(double amount) throws NotEnoughFundsException {
        double allowedBalance = maximumWithdrawToAccount();
        if (allowedBalance < amount) {
            throw new NotEnoughFundsException(this, allowedBalance);
        }
        setBalance(getBalance() - amount);
    }

    public long getDecimalBalanceValue() {
        return Math.round(balance);
    }

    @Override
    public boolean equals(Object o) {
        return (this == o) || ( (o instanceof AbstractAccount) && (this.id == ((AbstractAccount) o).id) );
    }

    @Override
    public int hashCode() {
        long temp = Double.doubleToLongBits(balance);
        return (int) (temp ^ (temp >>> 32));
    }
}
